// import store from '../store/index'
// import * as db from './db.js'

// let apiBaseUrl = 'http://www.shop.muliti.xyz'
// let apiBaseUrl = 'https://lph.tianlwl.com'
let apiBaseUrl = 'https://lph.tianlwl.com'

export default {
	config: {
		baseUrl: apiBaseUrl,
		data: {},
		method: "POST",
		dataType: "json",
		success() {},
		fail() {},
		complete() {}
	},
	interceptor: {
		request: null,
		response: null
	},
	request(options) {
		if (!options) {
			options = {}
		}

		options.baseUrl = options.baseUrl || this.config.baseUrl
		options.dataType = options.dataType || this.config.dataType
		options.url = options.baseUrl + options.url
		options.data = options.data || {}
		options.method = options.method || this.config.method
		options.header = {
			'Content-Type': 'application/json',
			'Authorization': uni.getStorageSync('lph-token') || ''
		}

		return new Promise((resolve, reject) => {
			let _config = null;

			// 请求完成
			options.complete = (response) => {
				if (this.interceptor.response) {
					let newResponse = this.interceptor.response(response)
					if (newResponse) {
						response = newResponse
					}
				}
				if (response.statusCode !== 200) {
					return uni.showToast({
						title: '网络错误，请重试！',
						icon: 'none'
					});
				}
				if (response.statusCode === 200) {
					let result = response.data
					// 请求失败的提示或返回
					if (result.code === 400 || result.code === 500) {
						return uni.showToast({
							title: result.message || '网络错误，请重试！',
							icon: 'none'
						});
					}
					// 未登陆的拦截
					if (result.code === 407) {
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						});
						setTimeout(() => {
							uni.navigateTo({
								url: '/pages/public/userLogin',
								animationType: 'slide-in-bottom'
							})
						}, 500)

						return false;
					}
					// 交换token
					if (result.code === 406) {
						uni.setStorageSync('userToken', result.data.token)
					}
					resolve(result);
				} else {
					reject(response);
				}
			}

			// 请求异常
			options.fail = (response) => {
				uni.showToast({
					title: '网络异常',
					icon: 'none',
					mask: true
				});
			}

			// 加载配置
			_config = Object.assign({}, this.config, options)
			if (this.interceptor.request) {
				this.interceptor.request(_config)
			}
			/*uni.showLoading({
				title: '数据加载中'
			});*/
			uni.request(_config);
		});
	},
}
